package com.isoftstone.disk.controllor;

import com.isoftstone.disk.entity.FileObsEntity;
import com.isoftstone.disk.service.DiskService;
import com.isoftstone.platform.controller.BaseController;
import com.isoftstone.platform.entity.PadingRstType;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class DiskControllor extends BaseController {
    private Logger logger = Logger.getLogger("DiskControllor");
    @Resource
    private DiskService diskService;
    @RequestMapping("/fileAll")
    public String showAll(){
        return  "file/fileAll";
    }
    @RequestMapping("/addFile")
    @ResponseBody
    public String addFile(MultipartHttpServletRequest request) throws IOException {


        CommonsMultipartFile cFile =
                (CommonsMultipartFile)request.getFile("filePath");
        String fileNameDesc = request.getParameter("fileName");
        FileItem fileItem =
                cFile.getFileItem();
        logger.info("fileNameDesc:" + fileNameDesc + ";filePath:" + fileItem.getName());
        if (fileItem.getName() == null
                || "".equals(fileItem.getName()))
        {
            return buildFailJsonMsg("up.load.fail",
                    null);
        }

        diskService.addFile(fileNameDesc,fileItem.getName(),cFile.getInputStream());
        return buildSuccessJsonMsg("file.upload.success",null);
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("files") MultipartFile[] files){
        for(MultipartFile file:files){
            File file1 ;
            String name="";
            try {
                logger.info("filePath:" + file.getOriginalFilename());
                if (file.getOriginalFilename() == null
                        || "".equals(file.getOriginalFilename()))
                {
                    return buildFailJsonMsg("up.load.fail",
                            null);
                }

                diskService.addFile("",file.getOriginalFilename(),file.getInputStream());
//                if (f instanceof CommonsMultipartFile) {
//                    //转换成这个对象，然后我们需要通过里面的FileItem来获得相对路径
//                    CommonsMultipartFile f2 = (CommonsMultipartFile) f;
//                    name = f2.getFileItem().getName();
//                    System.out.println(name + "        ---------相对路径");
//                    file1 = new File(getProjectPath() + "/" + name);
//                    file1.mkdirs();
//                    file1.createNewFile();
//                    f.transferTo(file1);
//                }
//                System.out.println(+"          "+file.getOriginalFilename()+"               "+file.getInputStream().toString());
//                System.out.println("---------------------------------------");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return buildSuccessJsonMsg("file.upload.success",null);
    }

    @RequestMapping("/getFileInfolist")
    @ResponseBody
    public PadingRstType<FileObsEntity> getFileInfolist() {
        PadingRstType<FileObsEntity> padingRstType = diskService.getFileInfolist();
        return padingRstType;
    }

    @RequestMapping(value = "/download/{fileId:.+}")
    @ResponseBody
    public ResponseEntity<byte[]> download(
            @PathVariable("fileId")
                    String fileId)
            throws IOException
    {
        ResponseEntity<byte[]> rsp = diskService.download(fileId);
        return rsp;
    }

    @RequestMapping(value = "/delete/{fileId:.+}")
    @ResponseBody
    public String delete(
            @PathVariable("fileId")
                    String fileId)
            throws IOException
    {
        if(fileId.isEmpty())
            return buildSuccessJsonMsg("file.delete.fail",null);
        diskService.delete(fileId);
        return buildSuccessJsonMsg("file.delete.success",null);
    }

    @RequestMapping(value = "/copy/{fileId:.+}")
    @ResponseBody
    public String copy(
            @PathVariable("fileId")
                    String fileId)
            throws IOException
    {
        if(fileId.isEmpty())
            return buildSuccessJsonMsg("file.copy.fail",null);
        diskService.copy(fileId);
        return buildSuccessJsonMsg("file.copy.success",null);
    }

    //[Liu]文件预览控制器
    @RequestMapping(value = "/preview/{fileId:.+}")
    @ResponseBody
    public String preview(
            @PathVariable("fileId")
                    String fileId)
            throws IOException {

        String tempUrl;
        System.out.println("[Liu Debug]:处于预览控制器~Now Preview Controller");
        if(fileId.isEmpty())
            return buildSuccessJsonMsg("file.delete.fail",null);
        tempUrl=diskService.preview(fileId);
        System.out.println("[Liu Debug]文件预览控制器~Preview Controller:(preview):tempUrl="+tempUrl);
        return "{\"id\":\"123.jpg\",\"type\":\"audio\",\"tempUrl\":\""+tempUrl+"\"}";
    }
}
